/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * add_order.java
 *
 * Created on Jul 25, 2011, 2:19:43 AM
 */
package introse1;

import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.swing.table.*;
import javax.swing.table.TableModel.*;
import javax.swing.JTable.*;
import java.sql.ResultSet;
import java.util.*;
import java.text.SimpleDateFormat;

/**
 *
 * @author Trisha
 */
public class add_order extends javax.swing.JFrame {

    /** Creates new form add_order */
    public add_order(manage_order manage_order) {
        initComponents();
        num = 0;
        numbertable.setText("");
        OrderNumber.setText("");
        try{
            pstmt = pangkonek.prepareStatement("Select MAX(order_id) FROM order_form");
            res = pstmt.executeQuery();
            while(res.next()){
                idnum = Integer.parseInt(res.getString(1));
            }
            idnum++;
            OrderNumber.setText(Integer.toString(idnum));
        }catch(Exception e){
            
        }
        ErrorHandler.setText("");
        Price.setText("");
        DefaultTableModel tmodel = (DefaultTableModel)Menu.getModel();
        ResultSet res;
        try{
            res = managing.getMenu();
            while(res.next()){
                String[] s1 = {res.getString("name_of_food"), res.getString("price")};
                tmodel.addRow(s1);
            }
        }catch(Exception e){}
        this.manage_order = manage_order;
        manage_order.setVisible(false);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        Menu = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        Order = new javax.swing.JTable();
        Add = new javax.swing.JButton();
        Delete = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        Save = new javax.swing.JButton();
        BackButton = new javax.swing.JButton();
        OrderNumber = new javax.swing.JLabel();
        ErrorHandler = new javax.swing.JLabel();
        Price = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tableNum = new javax.swing.JTextField();
        numbertable = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Rockwell", 0, 24));
        jLabel1.setText("Add Order");

        jLabel2.setFont(new java.awt.Font("Rockwell", 0, 18));
        jLabel2.setText("Order Number:");

        Menu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Item", "Price"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(Menu);
        Menu.getColumnModel().getColumn(0).setResizable(false);
        Menu.getColumnModel().getColumn(1).setResizable(false);

        Order.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Item", "Price"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(Order);
        Order.getColumnModel().getColumn(0).setResizable(false);
        Order.getColumnModel().getColumn(1).setResizable(false);

        Add.setFont(new java.awt.Font("Rockwell", 0, 18));
        Add.setIcon(new javax.swing.ImageIcon(getClass().getResource("/introse1/add.png"))); // NOI18N
        Add.setBorder(null);
        Add.setBorderPainted(false);
        Add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddActionPerformed(evt);
            }
        });

        Delete.setFont(new java.awt.Font("Rockwell", 0, 18));
        Delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/introse1/remove.png"))); // NOI18N
        Delete.setBorder(null);
        Delete.setBorderPainted(false);
        Delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Rockwell", 0, 18));
        jLabel3.setText("Total Price: ");

        Save.setFont(new java.awt.Font("Rockwell", 0, 18));
        Save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/introse1/save.png"))); // NOI18N
        Save.setBorder(null);
        Save.setBorderPainted(false);
        Save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveActionPerformed(evt);
            }
        });

        BackButton.setFont(new java.awt.Font("Rockwell", 0, 18));
        BackButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/introse1/back.png"))); // NOI18N
        BackButton.setBorder(null);
        BackButton.setBorderPainted(false);
        BackButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BackButtonActionPerformed(evt);
            }
        });

        OrderNumber.setText("jLabel4");

        ErrorHandler.setText("jLabel4");

        Price.setText("jLabel4");

        jLabel4.setText("Table Number:");

        numbertable.setText("jLabel5");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addGap(20, 20, 20)
                            .addComponent(Save)
                            .addGap(66, 66, 66)
                            .addComponent(BackButton))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel1)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(jLabel2)
                                            .addGap(18, 18, 18)
                                            .addComponent(OrderNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGap(126, 126, 126)
                                    .addComponent(ErrorHandler, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGap(165, 165, 165)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Add)
                            .addComponent(Delete))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(Price, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(38, 38, 38)
                        .addComponent(tableNum, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(numbertable, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(ErrorHandler))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(OrderNumber))
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tableNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(numbertable))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(Add)
                        .addGap(49, 49, 49)
                        .addComponent(Delete))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, 0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(Price))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(BackButton)
                    .addComponent(Save))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 656, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(50, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void AddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddActionPerformed
        try{
            DefaultTableModel tmodel = (DefaultTableModel)Order.getModel();
            String[] str = {(String)Menu.getModel().getValueAt(Menu.getSelectedRow(), 0), (String)Menu.getModel().getValueAt(Menu.getSelectedRow(), 1)};
            tmodel.addRow(str);
            String str21 = (String)Menu.getModel().getValueAt(Menu.getSelectedRow(), 1);
            int y = Integer.parseInt(str21);
            num += y;
            Price.setText(Integer.toString(num));
        }catch(Exception e){
            ErrorHandler.setText("Nothing was selected");
        }
    }//GEN-LAST:event_AddActionPerformed

    private void BackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackButtonActionPerformed
        this.setVisible(false);
        manage_order.setVisible(true);
    }//GEN-LAST:event_BackButtonActionPerformed

    private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteActionPerformed
        // TODO add your handling code here:
        try{
            DefaultTableModel tmodel = (DefaultTableModel)Order.getModel();
            int x = Order.getSelectedRow();
            String str21 = (String)Order.getModel().getValueAt(Order.getSelectedRow(), 1);
            int y = Integer.parseInt(str21);
            num -= y;
            Price.setText(Integer.toString(num));
            tmodel.removeRow(x);
        }catch(Exception e){
            ErrorHandler.setText("Nothing was selected");
        }
        
    }//GEN-LAST:event_DeleteActionPerformed

    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveActionPerformed
        // TODO add your handling code here:
        int tnum = 0;
        int bading = Order.getRowCount();
        int id = -1;
        float price = -1;
        ResultSet set;
        if(bading >  0){
            try{
                tnum = Integer.parseInt(tableNum.getText());
            }catch(Exception e){
                numbertable.setText("Required and must be a number");
            }
        
            if(num > 0){
                SimpleDateFormat timeStampFormat2 = new SimpleDateFormat("yyyy-MM-dd");
                String s1 = timeStampFormat2.format(new Date());;
                try{ 
                    pstmt = pangkonek.prepareStatement("Insert INTO order_form (date, tableNum, status, TotalPrice) VALUES(?,?,?,?)");
                    pstmt.setString(1, s1);
                    pstmt.setInt(2, tnum);
                    pstmt.setInt(3, 1);
                    pstmt.setFloat(4,num);
                    pstmt.executeUpdate();
                
                    for(int i = 0; i < bading; i++){
                        String str4 = (String)Order.getModel().getValueAt(i, 0);
                        pstmt = pangkonek.prepareStatement("Select * FROM recipe_file WHERE name_of_food = ?");
                        pstmt.setString(1, str4);
                        res = pstmt.executeQuery();
                        if(res.next()){
                            id = Integer.parseInt(res.getString("recipe_id"));
                            price = Float.parseFloat(res.getString("price"));
                        }
                        pstmt = pangkonek.prepareStatement("Insert INTO order_food(order_id, recipe_id, price) VALUES(?,?,?)");
                        pstmt.setInt(1,idnum);
                        pstmt.setInt(2, id);
                        pstmt.setFloat(3, price);
                        pstmt.executeUpdate();
                        
                        pstmt = pangkonek.prepareStatement("Select * from recipe_ingredient WHERE recipe_id = ?");
                        pstmt.setInt(1, id);
                        res = pstmt.executeQuery();
                        int inventid = -1;
                        float Quant = -1;
                        while(res.next()){
                            inventid = Integer.parseInt(res.getString("inventory_id"));
                            Quant = Float.parseFloat(res.getString("quantity"));
                            try{
                                pstmt = pangkonek.prepareStatement("Select * from inventory WHERE inventoryID = ?");
                                pstmt.setInt(1, inventid);
                                set = pstmt.executeQuery();
                                float ing = 0;
                                while(set.next()){
                                    ing = Float.parseFloat(set.getString("ingredientUsed"));
                                }
                                ing += Quant;
                                System.out.println(ing);
                                pstmt = pangkonek.prepareStatement("Update inventory set ingredientUsed = ? WHERE inventoryID = ?");
                                pstmt.setFloat(1, ing);
                                pstmt.setInt(2, inventid);
                                pstmt.executeUpdate();
                            }catch(Exception e){
                                ErrorHandler.setText("Unexpected Error");
                            }
                        }
                    }
                }catch(Exception e){
                    ErrorHandler.setText("An unexpected Error happened");
                }
            }
            else{
                ErrorHandler.setText("Nothing was ordered");
            }
        }
        else{
            ErrorHandler.setText("Nothing was ordered");
        }
    }//GEN-LAST:event_SaveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new add_order(manage_order).setVisible(true);
            }
        });
    }
    public static int num = 0;
    public static MenuManager managing = new MenuManager();
    private static manage_order manage_order;
    public static ResultSet res;
    public static PreparedStatement pstmt;
    public static DBConnect conn = new DBConnect();
    public static Connection pangkonek = conn.connect();
    public static int idnum = 0;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Add;
    private javax.swing.JButton BackButton;
    private javax.swing.JButton Delete;
    private javax.swing.JLabel ErrorHandler;
    private javax.swing.JTable Menu;
    private javax.swing.JTable Order;
    private javax.swing.JLabel OrderNumber;
    private javax.swing.JLabel Price;
    private javax.swing.JButton Save;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel numbertable;
    private javax.swing.JTextField tableNum;
    // End of variables declaration//GEN-END:variables
}
